package com.atguigu.eduService.controller;


import com.atguigu.commonutils.R;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.atguigu.eduService.client.VodClient;
import com.atguigu.eduService.entity.EduVideo;
import com.atguigu.eduService.service.EduVideoService;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * <p>
 * 课程视频 前端控制器
 * </p>
 *
 * @author atguigu
 * @since 2021-05-15
 */
@RestController
@RequestMapping("/eduService/video")
//@CrossOrigin
public class EduVideoController {
    @Resource
    private EduVideoService videoService;

    //注入vodClient
    @Resource
    private VodClient vodClient;

    //添加小节
    @PostMapping("addVideo")
    public R addVideo(@RequestBody EduVideo eduVideo) {
        boolean save = videoService.save(eduVideo);
        if (save)
            return R.ok();
        else
            return R.error();
    }

    //删除小节的时候，需要删除其中的视频
    @DeleteMapping("{id}")
    public R deleteVideo(@PathVariable String id) {
        //1.根据小节id获取视频id，调用方法实现视频删除
        EduVideo eduVideo = videoService.getById(id);
        String videoSourceId = eduVideo.getVideoSourceId();
        //如果包含视频id，则删除
        if (!StringUtils.isEmpty(videoSourceId)) {
            R result = vodClient.removeAlyVideo(id);
            if (result.getCode() == 20001 ){
                throw  new GuliException(20001,"删除视频失败，熔断器。。。。");
            }
        }
        //2.删除小节
        videoService.removeById(id);
        return R.ok();

    }

    //修改章节前需要数据回显
    @GetMapping("getVideoById/{videoId}")
    public R getVideoById(@PathVariable String videoId) {
        EduVideo video = videoService.getById(videoId);
        return R.ok().data("video", video);
    }

    //修改小节
    @PostMapping("updateVideo")
    public R updateVideo(@RequestBody EduVideo eduVideo) {
        boolean b = videoService.updateById(eduVideo);
        if (b)
            return R.ok();
        else
            return R.error();
    }
}

